package com.jin.webvideo.websocket.shareroom.entity;

import com.jin.webvideo.websocket.shareroom.ShareRoom;
import com.jin.webvideo.websocket.shareroom.ShareVideoInfo;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class BinMessageHandler {
    public BinMessage handle(BinMessage in, ShareRoom room) {
        byte[] bs = in.getPayload();
        ByteBuffer buffer = ByteBuffer.allocate(bs.length);
        buffer.put(bs);
        buffer.flip();
        ShareVideoInfo video = room.getVideoInfo();
        if (!BinMessage.isGetter(in)) {
            if (in.is(BinMessage.TYPE_CONTROL_ISPLAY)) {
                dealPlay(buffer, video);
            }
            if (in.is(BinMessage.TYPE_CONTROL_SPEED)) {
                dealSpeed(buffer, video);
            }
            if (in.is(BinMessage.TYPE_CONTROL_PROGRESS)) {
                dealProgress(buffer, video);
            }
            if (in.is(BinMessage.TYPE_CONTROL_SRC)) {
                dealSource(buffer, video);
            }
        }
        BinMessage out = dealGet(video);
        out.setBroadcast(BinMessage.BROADCAST_EXCEPT_SELF);
        if (BinMessage.isGetter(in)) {
            out.setBroadcast(BinMessage.BROADCAST_SEND_SELF);
        }
        return out;
    }

    protected void dealPlay(ByteBuffer buffer, ShareVideoInfo videoInfo) {
        byte bs = buffer.get();
        videoInfo.setStatus(bs == 1);
    }

    protected void dealSpeed(ByteBuffer buffer, ShareVideoInfo videoInfo) {
        float speed = buffer.getFloat();
        videoInfo.setSpeed(speed);
    }

    protected void dealProgress(ByteBuffer buffer, ShareVideoInfo videoInfo) {
        double progress = buffer.getDouble();
        videoInfo.setTime(progress);
    }


    protected void dealSource(ByteBuffer buffer, ShareVideoInfo videoInfo) {
        int remaining = buffer.remaining();
        byte[] bs = new byte[remaining];
        buffer.get(bs);
        String src = new String(bs);
        videoInfo.setUrl(src);
    }

    protected BinMessage dealGet(ShareVideoInfo videoInfo) {
        byte op = BinMessage.TYPE_CONTROL_ISPLAY | BinMessage.TYPE_CONTROL_SPEED |
                BinMessage.TYPE_CONTROL_PROGRESS | BinMessage.TYPE_CONTROL_SRC;

        byte[] url = videoInfo.getUrl().getBytes(StandardCharsets.UTF_8);
        ByteBuffer buffer = ByteBuffer.allocate(13 + url.length);
        buffer.put((byte) (videoInfo.isStatus()?1:0));
        buffer.putFloat(videoInfo.getSpeed());
        buffer.putDouble(videoInfo.getTime());
        buffer.put( url );
        byte[] bs = buffer.array();
        BinMessage a = BinMessage.createMessage(op, bs);
        return a;
    }
}
